package com.course.business.controller.web.discusspost.interceptor;

import com.alibaba.fastjson.JSON;
import com.course.server.domain.Member;
import com.course.server.dto.LoginMemberDto;
import com.course.server.util.CopyUtil;
import com.course.server.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginTicketInterceptor implements HandlerInterceptor {

    @Autowired
    private HostHolder hostHolder;

    @Resource(name="myRedisTemplate")
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            return true;
        }
        Object object = redisTemplate.opsForValue().get(token);//这其实是个String，强制转为了Object，但实际上还是一个String。

        if (object == null) {
            return true;
        } else {
            LoginMemberDto loginMemberDto= JSON.parseObject(String.valueOf(object), LoginMemberDto.class);
            Member member = CopyUtil.copy(loginMemberDto, Member.class);//把没能对应的字段赋值为null。
            hostHolder.setMember(member);   // 在本次请求中持有用户
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.clear();
    }
}
